package com.kai.kaiMybatis.sqlsession;

import com.kai.config.Function;
import com.kai.config.MapperBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author kai
 * @version 1.0
 * @date 2024/7/31
 * @Description  动态代理生成Mapper对象，调用kaiExecutor
 */
public class MapperProxy implements InvocationHandler {

    private kaiSqlSession kaisqlSession;
    private kaiConfiguration kaiconfiguration;
    private String mapperFile;

    public MapperProxy(kaiSqlSession kaisqlSession,
                       kaiConfiguration kaiconfiguration, Class clazz) {
        this.kaisqlSession = kaisqlSession;
        this.kaiconfiguration = kaiconfiguration;
        this.mapperFile = "com/kai/Mapper/"+clazz.getSimpleName() + ".xml";
    }


    /**
     * 动态代理
     *
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        MapperBean mapperBean = kaiconfiguration.readMapperxml(mapperFile);

        //判断是否是xml文件对应接口
        if (!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())) {
            return null;
        }

        //取出mapperBean的function
        List<Function> functions = mapperBean.getFunctions();
        //解析后xml是否有crud
        if (functions != null && functions.size() != 0) {
            for (Function func : functions) {
                //当前要执行的方法和mapper.xml中的ID一致，执行sql
                if (method.getName().equals(func.getFuncName())) {
                    //此处只考虑了selectone
                    if ("select".equalsIgnoreCase(func.getSqlType())) {

                        return kaisqlSession.selectone(func.getSql(), String.valueOf(args[0]));
                    }


                }
            }
        }

        return null;
    }



}
